package com.hmdp.service.impl;

import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.util.ArrayList;
import java.util.List;

import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TYPE_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    //使用list类型进行存储,每个value是对象的JSON形式
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryAllTypes() {
        // 查询Redis中是否有所有Type数据
        List<String> shopTypeList = stringRedisTemplate.opsForList().range(CACHE_SHOP_TYPE_KEY, 0, -1);

        // 非空则转换后返回
        if(!shopTypeList.isEmpty()){
            List<ShopType> myList = new ArrayList<>();
            for(String json : shopTypeList ){
                ShopType shopType = JSONUtil.toBean(json, ShopType.class);
                myList.add(shopType);
            }
            return Result.ok(myList);
        }

        // 没有则去数据库查询
        List<ShopType> shopTypes = this.query().orderByAsc("sort").list();
        // 将数据库查询的所有Type数据保存到Redis中并返回 -- 注意这个跟sort有关系,我们获取的是需要从大到小的sort值,需要修改为rightPush
        for(ShopType shopType : shopTypes){
            stringRedisTemplate.opsForList().rightPush(CACHE_SHOP_TYPE_KEY , JSONUtil.toJsonStr(shopType));
        }
        return Result.ok(shopTypes);
    }
}
